﻿using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Web.Mvc;
using YouWei.Infrastructure.Entity;
using YouWei.Infrastructure.Service;
using YouWei.Op.Common;
using YouWei.Op.Models.Account;
using YouWei.Utility;

namespace YouWei.Op.Controllers
{
    public class AccountController : BaseController
    {
        UserAccountService uaService = new UserAccountService();
        UserInfoService uService = new UserInfoService();

        //
        // GET: /Account/Login
        [AllowAnonymous]
        [HttpGet]
        public ActionResult Login()
        {
            string msg = GetParam("msg");
            ViewBag.Msg = msg;
            return View();
        }

        #region 登陆

        [AllowAnonymous]
        [HttpPost]
        public ActionResult Login(LoginModel model)
        {
            ResultData<string> rt = ValidLogin(model);
            if (rt.status != 0)
            {
                return ReturnResult(rt);
            }
            UserAccount ua = uaService.GetByLoginNum(model.UserName);
            if (ua == null)
            {
                rt.message = "用户名不存在.";
                rt.status = -1;
                return ReturnResult(rt);
            }

            if (MD5Helper.MD5String(model.UserName + ua.LoginPwd + "!!!") == model.Password)
            {
                //UserInfo usr = uService.SingleOrDefault(ua.UserID);
                FormsPrincipal.SignIn(new CurrentUser()
                {
                    //RoleID = ua.UserType,
                    UserId = ua.UserID,
                    //UserMobile = ua.Mobile,
                    UserName = ua.LoginNum
                }, 1);
            }
            else
            {
                rt.message = "密码错误.";
                rt.status = -1;
            }


            return ReturnResult(rt);
        }

        /// <summary>
        /// 验证码判断
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        private ResultData<string> ValidLogin(LoginModel model)
        {
            ResultData<string> rt = new ResultData<string>();
            if (string.IsNullOrEmpty(model.UserName))
            {
                rt.status = -1;
                rt.message = "请输入用户名";
                return rt;
            }
            if (string.IsNullOrEmpty(model.Password))
            {
                rt.status = -1;
                rt.message = "请输入密码";
                return rt;
            }

            if (string.IsNullOrWhiteSpace(model.ValidateCode))
            {
                rt.message = "验证码已失效，请重新输入验证码";
                rt.status = -1;
            }
            else if (Session["ValidateCode"] == null)
            {
                rt.message = "验证码已失效，请刷新验证码";
                rt.status = -1;
            }
            else if (Session["ValidateCode"].ToString().ToUpper() != model.ValidateCode.ToUpper())
            {
                rt.message = "验证码不正确,请重新输入";
                rt.status = -1;
            }
            return rt;
        }
        #endregion

        #region 验证码

        [AllowAnonymous]
        [HttpGet]
        public ActionResult GetValidateCode()
        {
            string randomCode = RandomHelper.GetRandWord(4);
            byte[] bytes = CreateValidateGraphic(randomCode);
            Session["ValidateCode"] = randomCode;
            return File(bytes, @"image/jpeg");
        }

        private byte[] CreateAuthCode(string str)
        {
            Font fn = new Font("宋体", 12);
            Brush forecolor = Brushes.Black;
            Brush bgcolor = Brushes.White;
            PointF pf = new PointF(5, 5);
            Bitmap bitmap = new Bitmap(100, 25);
            Rectangle rec = new Rectangle(0, 0, 100, 25);
            Graphics gh = Graphics.FromImage(bitmap);
            gh.FillRectangle(bgcolor, rec);
            gh.DrawString(str, fn, forecolor, pf);

            //画图片的边框线
            gh.DrawRectangle(new Pen(Color.Silver), 0, 0, bitmap.Width - 1, bitmap.Height - 1);

            //保存图片数据
            MemoryStream stream = new MemoryStream();
            bitmap.Save(stream, ImageFormat.Jpeg);
            //输出图片流
            return stream.ToArray();
        }

        public byte[] CreateValidateGraphic(string validateCode)
        {
            using (Bitmap map = new Bitmap(80, 30))
            {
                using (Graphics g = Graphics.FromImage(map))
                {
                    g.Clear(Color.White);//填充颜色
                    Random r = new Random();
                    //验证码
                    string[] font = { "黑体", "隶书", "楷体", "宋体", "微软雅黑" };
                    Brush[] B = { Brushes.Black, Brushes.Blue, Brushes.Red, Brushes.Green, Brushes.OrangeRed };
                    for (int i = 0; i < validateCode.Length; i++)
                    {
                        g.DrawString(validateCode[i].ToString(), new Font(font[i], 20), B[i], new Point(i * 15, 0));
                    }
                    //划线                    
                    for (int i = 0; i < 3; i++)
                    {
                        Point p1 = new Point(r.Next(0, map.Width), r.Next(map.Height));
                        Point p2 = new Point(r.Next(0, map.Width), r.Next(map.Height));
                        g.DrawLine(new Pen(Brushes.Red), p1, p2);
                    }
                }

                //保存图片数据
                MemoryStream stream = new MemoryStream();
                map.Save(stream, ImageFormat.Jpeg);
                //输出图片流
                return stream.ToArray();
            }
        }

        #endregion

        #region 登陆成功
        public ActionResult Index()
        {
            return View();
        }

        #endregion

        #region 注销
        public ContentResult LoginOut()
        {
            ResultData<string> rt = new ResultData<string>();
            try
            {
                FormsPrincipal.SignOut();
            }
            catch (Exception ex)
            {
                rt.data = ex.Message;
                rt.status = -1;
                rt.message = "注销失败";
            }
            return ReturnResult(rt);
        }
        #endregion
    }
}